package net.pm.core.service.impl;

import javax.annotation.Resource;

import net.pm.common.dao.GenericDao;
import net.pm.common.service.impl.GenericServicerImpl;
import net.pm.common.toolkit.PMTool;
import net.pm.common.toolkit.Pager;
import net.pm.common.toolkit.date.DateUtils;
import net.pm.core.entities.db.Material;
import net.pm.core.service.MaterialServicer;
import net.pm.core.service.MateriallogServicer;

import org.springframework.stereotype.Service;

@Service("MaterialServicer")
public class MaterialServicerImpl extends GenericServicerImpl<Material, Long>
		implements MaterialServicer {

	@Resource(name = "MaterialDao")
	@Override
	public void setGenericDao(GenericDao<Material, Long> genericDao) {
		super.genericDao = genericDao;
	}

	@Resource(name = "MateriallogServicer")
	private MateriallogServicer materiallogServicer;

	@Override
	public Long createMaterial(Material material) {
		// setter 一些默认属性
		material.setAddTime(DateUtils.obtainCurrentDate());
		if (PMTool.isNotEmpty(super.create(material))) {
			return MaterialServicer.create_material_success;
		}
		return MaterialServicer.create_material_failed;
	}

	@Override
	public Pager<Material> findMaterialPager(Integer pagesize, Integer pageno,
			String materialName) {
		final StringBuilder builder = new StringBuilder(
				"from Material material where 1=1 ");
		Boolean ishasval = false;
		if (ishasval = PMTool.isNotEmpty(materialName)) {
			builder.append(" and material.materialName like ? ");
			materialName = "%".concat(materialName).concat("%");
		}
		builder.append(" order by material.addTime ");

		if (ishasval)
			return super.findPagerByJpql(pagesize, pageno, builder,
					materialName);
		return super.findPagerByJpql(pagesize, pageno, builder);
	}

	@Override
	public Material findMaterialById(Long materialId) {
		Material material = super.findEntityById(materialId);
		material.setLogs(materiallogServicer
				.findMateriallogByMaterialId(materialId));
		return material;
	}

	@Override
	public Long collarMaterial(Long materialId, Integer getNumber) {
		Material material = super.findEntityById(materialId);
		material.setInventoryNumber(material.getInventoryNumber() - getNumber);
		super.modify(material);
		return MaterialServicer.collar_material_suceess;
	}

}
